package problem738;

//738.单调递增的数字
//https://leetcode.cn/problems/monotone-increasing-digits/

class Solution {
    public int monotoneIncreasingDigits(int n) {
        char[] s = String.valueOf(n).toCharArray();
        int len = s.length;
        int i = 0;
        while(i < len-1) {
            if(s[i] > s[i+1]) {
                break;
            }
            i++;
        }
        if(i == len-1) return n;
        
        while(i>0 && s[i-1] == s[i]) {
            i--;
        }
        s[i] = (char)(s[i]-1);
        for(int j = i+1; j<s.length; j++) {
            s[j] = '9';
        }
        return Integer.valueOf(String.valueOf(s));
    }
}